//
//  QDloadTempletVC.m
//  ImageEffect
//
//  Created by lichq on 14-1-27.
//  Copyright (c) 2014年 lichq. All rights reserved.
//

#import "QDloadTempletVC.h"
#import "QTempletVC.h"
#import "QStruct.h"
#import "QTempletFile.h"

@interface QDloadTempletVC ()

@end

@implementation QDloadTempletVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)createAllTempletInfoFile{
    for (int i = 0; i < all_tpTitleArray.count; i++) {
        QTempletInfo templetInfo;
        switch (i) {
            case 0:
                templetInfo = createTempletInfo0();
                break;
            case 1:
                templetInfo = createTempletInfo1();
                break;
            case 2:
                templetInfo = createTempletInfo2();
                break;
            case 3:
                templetInfo = createTempletInfo3();
                break;
                
            default:
                break;
        }
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDir = [paths objectAtIndex:0];
        NSString *templetTitle = [all_tpTitleArray objectAtIndex:i];
        NSString *filePath = [NSString  stringWithFormat:@"%@/%@", docDir, templetTitle];
        
        writeTempletInfoToFile(templetInfo, (char *)[filePath UTF8String]);
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStyleBordered target:self action:@selector(goOK)];
    self.navigationItem.rightBarButtonItem = right;
    
    UITableView *tv = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStylePlain];
    tv.dataSource = self;
    tv.delegate = self;
    [self.view addSubview:tv];
    
    all_tpTitleArray = [[NSMutableArray alloc]initWithObjects:@"三角", @"上下", @"五块", @"斜躺", nil];//From Net
//    [self createAllTempletInfoFile];
    NSArray *m_titleArrayTemp = [[NSUserDefaults standardUserDefaults] arrayForKey:@"templetTitle"];
    m_tpTitleArray = [[NSMutableArray alloc]initWithArray:m_titleArrayTemp];
    all_urlArrayOfImage = [[NSMutableArray alloc]initWithObjects:@"http://1.jpg", @"http://2.jpg", @"http:3",@"http", nil];
    m_urlArrayOfImage = [[NSMutableArray alloc]init];
}




- (void)goOK{
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [all_tpTitleArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"CInd"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CInd"];
    }
    cell.textLabel.text = [all_tpTitleArray objectAtIndex:indexPath.row];
    NSURL *url = [NSURL URLWithString:[all_urlArrayOfImage objectAtIndex:indexPath.row]];
    NSData *myImageData  = [[NSData alloc]initWithContentsOfURL:url];
    UIImage *image = [[UIImage alloc]initWithData:myImageData scale:1];
    cell.imageView.image = image;
    
    NSString *templetTitle = [all_tpTitleArray objectAtIndex:indexPath.row];
    if (m_tpTitleArray != nil && [m_tpTitleArray containsObject:templetTitle]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType == UITableViewCellAccessoryNone) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        
        [self goDloadTempletInfo:indexPath.row];
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)goDloadTempletInfo:(NSInteger)selIndex{
    NSString *downTpTitle = [all_tpTitleArray objectAtIndex:selIndex];
    [m_tpTitleArray addObject:downTpTitle];
    [[NSUserDefaults standardUserDefaults] setObject:m_tpTitleArray forKey:@"templetTitle"];
    
//    NSURL *downImageURL = [all_urlArrayOfImage objectAtIndex:selIndex];
//    [self goDloadImageByURL:downImageURL isSynchronous:YES];
}


- (void)goDloadImageByURL:(NSURL *)url isSynchronous:(BOOL)isSynchronous{
    /*
     //直接通过URL获取图片
     NSURL *url = [NSURL URLWithString:[all_urlArrayOfImage objectAtIndex:indexPath.row]];
     
     NSData *myImageData  = [[NSData alloc]initWithContentsOfURL:url];
     UIImage *image = [[UIImage alloc]initWithData:myImageData scale:1];
     imageView.image = image;
     */
    
    //Get请求：
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    if (isSynchronous) {
        //Get请求：同步
        NSMutableData *dataReceived = (NSMutableData *)[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        
        NSString *receiveStr = [[NSString alloc]initWithData:dataReceived encoding:NSUTF8StringEncoding];
        NSLog(@"receiveStr = %@",receiveStr);
        
        UIImage *image = [[UIImage alloc]initWithData:dataReceived scale:1];
        
        /*
         NSArray *nameAry=[@"http://www.huimg.cn/public/myPortrait.png" componentsSeparatedByString:@"/"];
         NSString *downloadPictName = [nameAry objectAtIndex:[nameAry count]-1];
         [self saveFileData:dataReceived ToDocumentByFileName:downloadPictName];
         */
        [self saveImageToPhotosAlbum:image];
    }else{
        //Get请求：异步
        NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
        if (connection != nil) {
            NSLog(@"Create the connection: Successfully !");
        }else{
            NSLog(@"Create the connection: Failed !");
        }
    }
}

- (void)saveFileData:(NSData *)m_dataReceived ToDocumentByFileName:(NSString *)downloadFileName{
    NSString *documentsDirectory = [self getDocumentsDirectory];
    NSString *filePathString = [documentsDirectory stringByAppendingString:downloadFileName];
    if ([m_dataReceived writeToFile:filePathString atomically:YES]) {
        NSLog(@"保存成功");
    }else{
        NSLog(@"保存失败");
    }
}

- (NSString *)getDocumentsDirectory{
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    /* Methor 2:
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     NSString *documentsDirectory = [paths objectAtIndex:0];
     */
    return documentsDirectory;
}

- (void)saveImageToPhotosAlbum:(UIImage *)image{
    UIImageWriteToSavedPhotosAlbum(image, self,@selector(image:didFinishSavingWithError:contextInfo:), nil);
}


- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error != NULL){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"保存失败,请重新保存" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil, nil];
        [alert show];
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"保存成功" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil, nil];
        [alert show];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
